package com.link.linkupjavaweb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.link.linkupjavaweb.common.ItemPriceConfig;
import com.link.linkupjavaweb.entity.GameItem;
import com.link.linkupjavaweb.entity.User;
import com.link.linkupjavaweb.entity.UserItem;
import com.link.linkupjavaweb.mapper.GameItemMapper;
import com.link.linkupjavaweb.mapper.UserItemMapper;
import com.link.linkupjavaweb.mapper.UserMapper;
import com.link.linkupjavaweb.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 道具Service实现类
 */
@Service
public class ItemServiceImpl implements ItemService {
    
    @Autowired
    private UserItemMapper userItemMapper;
    
    @Autowired
    private GameItemMapper gameItemMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public Map<String, Integer> getUserItems(Long userId) {
        Map<String, Integer> itemMap = new HashMap<>();
        
        // 查询用户所有道具
        QueryWrapper<UserItem> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<UserItem> userItems = userItemMapper.selectList(wrapper);
        
        // 转换为Map
        for (UserItem userItem : userItems) {
            GameItem gameItem = gameItemMapper.selectById(userItem.getItemId());
            if (gameItem != null) {
                itemMap.put(gameItem.getItemCode(), userItem.getItemCount());
            }
        }
        
        return itemMap;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean useItem(Long userId, String itemCode) {
        // 查询道具
        GameItem gameItem = gameItemMapper.selectByItemCode(itemCode);
        if (gameItem == null) {
            return false;
        }
        
        // 查询用户道具
        QueryWrapper<UserItem> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("item_id", gameItem.getId());
        UserItem userItem = userItemMapper.selectOne(wrapper);
        
        if (userItem == null || userItem.getItemCount() <= 0) {
            return false;
        }
        
        // 减少数量
        int result = userItemMapper.decreaseItemCount(userId, gameItem.getId());
        return result > 0;
    }
    
    @Override
    public int getItemCount(Long userId, String itemCode) {
        // 查询道具
        GameItem gameItem = gameItemMapper.selectByItemCode(itemCode);
        if (gameItem == null) {
            return 0;
        }
        
        // 查询用户道具
        QueryWrapper<UserItem> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("item_id", gameItem.getId());
        UserItem userItem = userItemMapper.selectOne(wrapper);
        
        return userItem != null ? userItem.getItemCount() : 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int purchaseItem(Long userId, String itemCode, Integer quantity) throws Exception {
        // 1. 验证购买数量
        if (quantity == null || quantity <= 0) {
            throw new Exception("购买数量必须大于0");
        }
        
        if (quantity > 99) {
            throw new Exception("单次购买数量不能超过99个");
        }
        
        // 2. 查询道具信息
        GameItem gameItem = gameItemMapper.selectByItemCode(itemCode);
        if (gameItem == null) {
            throw new Exception("道具不存在");
        }
        
        if (gameItem.getStatus() != 0) {
            throw new Exception("该道具已下架");
        }
        
        // 3. 计算总价
        Integer totalPrice = ItemPriceConfig.calculateTotal(itemCode, quantity);
        if (totalPrice == null || totalPrice <= 0) {
            throw new Exception("道具价格配置错误");
        }
        
        // 4. 查询用户积分
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new Exception("用户不存在");
        }
        
        if (user.getTotalScore() < totalPrice) {
            throw new Exception("积分不足，需要" + totalPrice + "积分，当前仅有" + user.getTotalScore() + "积分");
        }
        
        // 5. 扣除积分
        user.setTotalScore(user.getTotalScore() - totalPrice);
        userMapper.updateById(user);
        
        // 6. 增加道具数量
        QueryWrapper<UserItem> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("item_id", gameItem.getId());
        UserItem userItem = userItemMapper.selectOne(wrapper);
        
        if (userItem == null) {
            // 首次购买，创建记录
            userItem = new UserItem();
            userItem.setUserId(userId);
            userItem.setItemId(gameItem.getId());
            userItem.setItemCount(quantity);
            userItem.setCreateTime(LocalDateTime.now());
            userItemMapper.insert(userItem);
        } else {
            // 已有记录，增加数量
            userItem.setItemCount(userItem.getItemCount() + quantity);
            userItemMapper.updateById(userItem);
        }
        
        return userItem.getItemCount();
    }
    
    @Override
    public Map<String, Object> getItemShop() {
        Map<String, Object> shop = new HashMap<>();
        
        // 获取所有启用的道具
        QueryWrapper<GameItem> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0);
        wrapper.orderByAsc("id");
        List<GameItem> items = gameItemMapper.selectList(wrapper);
        
        // 构建商店数据
        List<Map<String, Object>> itemList = new ArrayList<>();
        for (GameItem item : items) {
            Map<String, Object> itemData = new HashMap<>();
            itemData.put("itemCode", item.getItemCode());
            itemData.put("itemName", item.getItemName());
            itemData.put("description", item.getDescription());
            itemData.put("iconUrl", item.getIconUrl());
            itemData.put("itemType", item.getItemType());
            itemData.put("price", ItemPriceConfig.getPrice(item.getItemCode()));
            itemList.add(itemData);
        }
        
        shop.put("items", itemList);
        shop.put("total", itemList.size());
        
        return shop;
    }
}

